from django.shortcuts import render, HttpResponse, redirect
import collections
from web import models
from django.db.models import Count
import datetime
from django.http import JsonResponse
import time


def dashboard(request, project_id):
    # 问题数据处理(类似一个有序{}版本不同)
    status_dict = collections.OrderedDict()
    # 问题类型
    for key, text in models.Issues.status_choices:
        # 问题类型和筛选(默认是0后面添加)
        status_dict[key] = {'text': text, 'count': 0}
    # 当前项目的状态(再通过id求和)<QuerySet [{'status': 1, 'ct': 8}, {'status': 2, 'ct': 1}]>
    issues_data = models.Issues.objects.filter(project_id=project_id).values('status').annotate(ct=Count('id'))
    for item in issues_data:
        status_dict[item['status']]['count'] = item['ct']
    # 项目成员
    user_list = models.ProjectUser.objects.filter(project_id=project_id).values('user_id', 'user__username')
    # 最近的10个问题(更新信息不为空的,从最新的到最后的更新信息)
    top_ten = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by('-id')[0:10]

    context = {
        'status_dict': status_dict,
        'user_list': user_list,
        'top_ten_object': top_ten,
    }
    return render(request, 'dashboard.html', context)


def issues_chart(request, project_id):
    date_dict = collections.OrderedDict()
    today = datetime.datetime.now().date()
    # 类似[('2021-02-12', [1613059200000.0, 0],)  <[1613059200000.0, 0]>这个是我们要获取的后面会用values拿走，分别是当天时间，即问题个数
    for i in range(0, 30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]
    # 获取30天内每天创建时间的问题数(ctime代表类似2021-02-11的时间格式,没创建就是空)
    result = models.Issues.objects.filter(project_id=project_id,
                                          create_datetime__gte=today - datetime.timedelta(days=30)).extra(
        select={'ctime': "DATE_FORMAT(web_issues.create_datetime,'%%Y-%%m-%%d')"}).values('ctime').annotate(
        ct=Count('id'))

    for item in result:
        date_dict[item['ctime']][1] = item['ct']
    return JsonResponse({'status': True, 'data': list(date_dict.values())})
